package com.irdstudio.efp.esb.api.rest.yed.interfaceManage;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.irdstudio.basic.framework.core.constant.ESBConstant;
import com.irdstudio.basic.framework.core.constant.EsbRetCodeStandard;
import com.irdstudio.basic.framework.core.exception.BizException;
import com.irdstudio.basic.framework.core.exception.ESBException;
import com.irdstudio.basic.framework.core.util.StringUtil;
import com.irdstudio.efp.edoc.service.bo.UpLoadFileVO;
import com.irdstudio.efp.edoc.service.facade.UpLoadFileService;
import com.irdstudio.efp.esb.api.common.EsbRespServiceBeanCreator;
import com.irdstudio.efp.esb.api.rest.EsbController;
import com.irdstudio.efp.esb.api.rest.yed.req.CrdtInf;
import com.irdstudio.efp.esb.api.rest.yed.req.ReqCompreAuthLetterBean;
import com.irdstudio.efp.esb.api.rest.yed.resp.CompreAuthLetterInfo;
import com.irdstudio.efp.esb.api.rest.yed.resp.RespCompreAuthLetterBean;
import com.irdstudio.efp.esb.common.constant.EsbBizEnums;
import com.irdstudio.efp.esb.common.constant.EsbSysHeadEnums;
import com.irdstudio.efp.esb.common.server.req.EsbReqServiceBean;
import com.irdstudio.efp.esb.common.server.resp.EsbRespServiceBean;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

/**
 * 需求编号：xxxxxx<br/>
 * 问题编号：<br/>
 * 功能描述：综合委托授权书查询<br/>
 * 创建时间：2020/8/5 10:51
 *
 * @Author tiankg
 * @Version 1.0
 * @Since 1.0
 */
@RestController
@RequestMapping("/esb")
public class ComprehensiveAuthLetterController implements EsbController {
    private static Logger logger = LoggerFactory.getLogger(ComprehensiveAuthLetterController.class);

    @ModelAttribute("esbReqServiceBean")
    public EsbReqServiceBean getReqEsbHeadBean(HttpServletRequest request) {
        logger.info("获取ESB请求对象，校验 ESB请求系统头和请求应用头对象开始");
        EsbReqServiceBean esbReqServiceBean = (EsbReqServiceBean) request.getAttribute("esbReqServiceBean");
        return esbReqServiceBean;
    }

    @ModelAttribute("reqCompreAuthLetterBean")
    public ReqCompreAuthLetterBean getReqEsbBodyBean(HttpServletRequest request) {
        logger.info("获取综合委托授权书查询接口请求对象，校验综合委托授权书查询接口请求体对象开始");
        String esbReqBody = (String) request.getAttribute("esbReqBody");
        return JSONObject.parseObject(esbReqBody, ReqCompreAuthLetterBean.class);
    }

    @PostMapping("/SERVICE_30230011_03")
    public EsbRespServiceBean doRecv(@Validated @ModelAttribute("esbReqServiceBean") EsbReqServiceBean esbReqServiceBean, BindingResult br1,
                                     @Validated @ModelAttribute("reqCompreAuthLetterBean") ReqCompreAuthLetterBean reqCompreAuthLetterBean, BindingResult br2, Exception exception) {
        String globalSerno = esbReqServiceBean.getSysHead().getGlblSrlNo();
        logger.info("优e贷综合委托授权书查询接口处理开始,全局流水号为：[{}]", globalSerno);

        RespCompreAuthLetterBean resp = new RespCompreAuthLetterBean();
        try {
            if (reqCompreAuthLetterBean.getCrdtInfArry().size() <= 0){
                throw new BizException(EsbRetCodeStandard.JKYDCSJYBTG.getValue(), "传入的参数为空！");
            }
            String crd =  reqCompreAuthLetterBean.getCrdtInfArry().get(0).getCrNo();
            if (StringUtil.isNullorBank(crd)){
                throw new ESBException(EsbRetCodeStandard.JKYDCSJYBTG.getValue(),"字段：CrNo -- 不能为空，当前值"+reqCompreAuthLetterBean.getCrdtInfArry().get(0).getCrNo());
            }

            for (CrdtInf crdtInf:reqCompreAuthLetterBean.getCrdtInfArry()) {
                UpLoadFileVO upLoadFileQueryVO = new UpLoadFileVO();
                upLoadFileQueryVO.setApplySeq(crdtInf.getCrNo());
                List<UpLoadFileVO> upLoadFileVOList =  upLoadFileService.qryInfosByApplySeq(upLoadFileQueryVO);
                if(Objects.nonNull(upLoadFileVOList)){
                    for (UpLoadFileVO upLoadFileVO:upLoadFileVOList) {
                        CompreAuthLetterInfo compreAuthLetterInfo = CompreAuthLetterInfo.builder()
                                .imgSrlNo(StringUtils.isEmpty(upLoadFileVO.getApplySeq())?"":upLoadFileVO.getApplySeq())
                                .imgTp(StringUtils.isEmpty(upLoadFileVO.getImageType())?"":upLoadFileVO.getImageType())
                                .genrtTm(StringUtils.isEmpty(upLoadFileVO.getStartDate())?"":upLoadFileVO.getStartDate())
                                .rpySt(StringUtils.isEmpty(upLoadFileVO.getState())?"":upLoadFileVO.getState())
                                .stIndr(StringUtils.isEmpty(upLoadFileVO.getStateNum())?"":upLoadFileVO.getStateNum())
                                .btchNo(StringUtils.isEmpty(upLoadFileVO.getBatch())?"":upLoadFileVO.getBatch())
                                .upldFilePth(StringUtils.isEmpty(upLoadFileVO.getFilePath())?"":upLoadFileVO.getFilePath())
                                .crtTm(StringUtils.isEmpty(upLoadFileVO.getCreateTime())?"":upLoadFileVO.getCreateTime())
                                .rctlyMdfTm(StringUtils.isEmpty(upLoadFileVO.getLastModifyTime())?"":upLoadFileVO.getLastModifyTime())
                                .apndFileSt(StringUtils.isEmpty(upLoadFileVO.getAddFileState())?"":upLoadFileVO.getAddFileState())
                                .identNo(StringUtils.isEmpty(upLoadFileVO.getCertCode())?"":upLoadFileVO.getCertCode())
                                .custNm(StringUtils.isEmpty(upLoadFileVO.getCusName())?"":upLoadFileVO.getCusName())
                                .pdNm(StringUtils.isEmpty(upLoadFileVO.getPrdName())?"":upLoadFileVO.getPrdName())
                                .build();
                        resp.getImgPlatInfArry().add(compreAuthLetterInfo);
                    }
                }else{
                    logger.info("根据流水号未查到影像平台信息，流水号为：" + crdtInf.getCrNo());
                    continue;
                }
            }

            return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
                    JSON.toJSONString(buildRespCompreAuthLetterBean(ESBConstant.SUCCESS, "查询成功", resp)),
                    EsbSysHeadEnums.RetStEnum.SUCCESS.getCode(),
                    EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(),
                    "查询成功");
        } catch (BizException bize) {
            logger.error("***********调用综合委托授权书查询接口处理失败****************************" + bize.getMessage());
            return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
                    JSON.toJSONString(buildRespCompreAuthLetterBean(EsbBizEnums.RetCodeEnum.YWLJCLYC.getVALUE(), bize.getMessage(), resp)),
                    EsbSysHeadEnums.RetStEnum.FAILURE.getCode(),
                    EsbBizEnums.RetCodeEnum.YWLJCLYC.getVALUE(),
                    bize.getMessage());
        } catch (Exception e) {
            logger.error("***********调用综合委托授权书查询接口处理失败************************" + e.getMessage());
            return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
                    JSON.toJSONString(buildRespCompreAuthLetterBean(EsbBizEnums.RetCodeEnum.OTHERS_EXCEPTION.getVALUE(), e.getMessage(), resp)),
                    EsbSysHeadEnums.RetStEnum.FAILURE.getCode(),
                    EsbBizEnums.RetCodeEnum.OTHERS_EXCEPTION.getVALUE(),
                    e.getMessage());
        } finally {
            logger.info("优e贷综合委托授权书查询接口处理结束,全局流水号为：[{}]", globalSerno);
        }
    }

    @Autowired
    @Qualifier("upLoadFileService")
    private UpLoadFileService upLoadFileService;

    /**
     * 创建RespBean
     * @param retCode
     * @param retMsg
     * @return
     */
    private RespCompreAuthLetterBean buildRespCompreAuthLetterBean(String retCode, String retMsg,RespCompreAuthLetterBean resp) {
        resp.setRetCd(retCode);
        resp.setRetMsg(retMsg);
        return resp;
    }

}
